package cn.xyhelp.shop.user.service.impl;

import cn.xyhelp.shop.user.dao.mapper.UserMapper;
import cn.xyhelp.shop.user.dto.WxUserSimpleInfoDTO;
import cn.xyhelp.shop.user.model.entity.User;
import cn.xyhelp.shop.user.model.entity.UserAuth;
import cn.xyhelp.shop.user.service.UserAuthService;
import cn.xyhelp.shop.user.service.UserService;
import cn.xyhelp.shop.user.vo.UserAllInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.Assert;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author xushengquan
 * @since 2022-03-19
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    UserAuthService userAuthService;

    public boolean teatAddUser(User user) {
        boolean result = save(user);
        return result;
    }


    /**
     * 创建一个用户
     *
     * @param userAllInfo 用户所有信息
     * @return 是否创建成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean createUser(UserAllInfo userAllInfo) {
        Assert.notNull(userAllInfo, "用户信息不能为null");
        boolean result = save(userAllInfo.getUser());
        if (result) {
            userAllInfo.getUserAuth().setUserId(userAllInfo.getUser().getId());
            result = userAuthService.save(userAllInfo.getUserAuth()) ;
        }
        if (!result) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return result;
    }
    /**
     * 返回一个UserAllInfo对象
     *
     *  WxUserSimpleInfoDT 微信返回的用户信息
     * @return 是否创建成功
     */
    public UserAllInfo generateUserAllInfo(WxUserSimpleInfoDTO userSimpleInfo) {
        User user = new User()
                .setName(userSimpleInfo.getName())
                .setAvatarUrl(userSimpleInfo.getAvatar())
                .setCoin(0)
                .setPreferStoreId(0);
                //.setFromType()//11111111111111111111111
                //.setFromId()
                ;
        UserAuth userAuth = new UserAuth()
                .setIdentity(userSimpleInfo.getOpenId())
                .setType(1);//22222222222222222222

        return new UserAllInfo()
                .setUser(user)
                .setUserAuth(userAuth);
    }
}
